using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WCS.Infrastructure.Dto.Request.Order;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Service.Interface;

namespace WCS.Service.Instance
{
    /// <summary>
    /// 模拟订单数据定时后台服务
    /// </summary>
    public class OrderSimulationBackgroundService : BackgroundService
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<OrderSimulationBackgroundService> _logger;
        private readonly IServiceProvider _serviceProvider;
        private readonly Random _random;

        public OrderSimulationBackgroundService(
        ILogger<OrderSimulationBackgroundService> logger,
        IServiceProvider serviceProvider,
        IConfiguration configuration)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
            _configuration = configuration;
            _random = new Random();
        }

        // 固定的CodeId列表
        private readonly List<string> _codeIds = new List<string>
        {
            "08ddead43f42bafbf58d76108801687a",
            "08ddeb5cdb649f2af58d76b31e0477a9",
            "08ddf11115094973f58d76893f0112bd",
            "08ddf111c35393ccf58d76893f0112c2",
            "08ddf111fbcc7b9ff58d76893f0112da",
            "08ddf111cfb7bba5f58d76893f0112c4",
            "08ddf111d87c7009f58d76893f0112c6",
            "08ddf111d894bc46f58d76893f0112c8",
            "08ddf111d96bece2f58d76893f0112ca",
            "08ddf111e0b7a3f9f58d76893f0112cc",
            "08ddf111e7cea66ef58d76893f0112d1",
            "08ddf111ee11ad7af58d76893f0112d3",
            "08ddf111f5c9c19cf58d76893f0112d5"
        };

        // 固定的CouponInstanceId列表
        private readonly List<string> _couponInstanceIds = new List<string>
        {
            "08ddeb5e749cc30f7a2d7e1f24024dd0",
            "08ddeb5e74a2399d7a2d7e1f24024dd1",
            "08ddeb5e74a722417a2d7e1f24024dd2", 
            //"coupon_004",
            //"coupon_005"
        };

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    // 检查当前时间是否在禁止执行的时间段内（凌晨1点到早上9点）
                    //var currentHour = DateTime.Now.Hour;
                    //if (currentHour >= 1 && currentHour < 9)
                    //{
                    //    _logger.LogInformation($"当前时间 {DateTime.Now:HH:mm} 在禁止执行时间段内（01:00-09:00），跳过任务执行");

                    //    // 计算到早上9点的等待时间
                    //    var now = DateTime.Now;
                    //    var nextRunTime = now.Date.AddHours(9);
                    //    if (now.Hour >= 9)
                    //    {
                    //        nextRunTime = nextRunTime.AddDays(1);
                    //    }

                    //    var waitTime = nextRunTime - now;
                    //    _logger.LogInformation($"将在 {nextRunTime:yyyy-MM-dd HH:mm:ss} 恢复任务执行");

                    //    await Task.Delay(waitTime, stoppingToken);
                    //    continue;
                    //}

                    ////// 生成5-20分钟的随机执行间隔
                    ////var randomMinutes = _random.Next(1, 5); // 1到5分钟
                    ////_logger.LogInformation($"下次任务将在 {randomMinutes} 分钟后执行");

                    // 强制把配置值转成 int（不做校验）
                    var minSeconds = int.Parse(_configuration["OrderSimulation:MinTime"]!);
                    var maxSeconds = int.Parse(_configuration["OrderSimulation:MaxTime"]!);

                    // Random.Next 上限不包含，+1 使其包含 maxSeconds
                    var randomSeconds = _random.Next(minSeconds, maxSeconds + 1);
                    _logger.LogInformation($"下次任务将在 {randomSeconds} 秒钟后执行");

                    await Task.Delay(TimeSpan.FromSeconds(randomSeconds), stoppingToken);

                    if (!stoppingToken.IsCancellationRequested)
                    {
                        //    // 再次检查时间（防止在等待期间进入禁止时间段）
                        //    currentHour = DateTime.Now.Hour;
                        //    if (currentHour >= 1 && currentHour < 9)
                        //    {
                        //        _logger.LogInformation($"等待期间进入禁止执行时间段，跳过本次任务");
                        //        continue;
                        //    }

                        await ExecuteOrderSimulationTask();
                    }
                }
                catch (OperationCanceledException)
                {
                    // 服务被取消，正常退出
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "模拟订单任务执行异常");
                    // 发生异常时等待1分钟后重试
                    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
                }
            }
        }

        private async Task ExecuteOrderSimulationTask()
        {
            try
            {
                _logger.LogInformation($"开始执行模拟订单任务: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");

                await using var scope = _serviceProvider.CreateAsyncScope();
                var paymentService = scope.ServiceProvider.GetRequiredService<IPaymentService>();

                // 生成随机订单数据
                var orderDto = GenerateRandomOrderData();

                var result = await paymentService.AddOrdersSimulationAsync(orderDto);

                if (result.code == ApiCode.ok)
                {
                    _logger.LogInformation($"模拟订单创建成功，订单金额: {orderDto.OrderAmount / 100.0:F2}元");
                }
                else
                {
                    _logger.LogWarning($"模拟订单创建失败: {result.message}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行模拟订单任务时发生异常");
            }
        }

        private OrderCreateRequestDto GenerateRandomOrderData()
        {
            // 生成4.9到49.9之间的随机金额（以分为单位）
            //var orderAmount = _random.Next(490, 4991); // 490分到4990分
            var minSeconds = int.Parse(_configuration["OrderSimulation:MinAmount"]!);
            var maxSeconds = int.Parse(_configuration["OrderSimulation:MaxAmount"]!);

            // Random.Next 上限不包含，+1 使其包含 maxSeconds
            var orderAmount = _random.Next(minSeconds, maxSeconds + 1);

            // 随机选择CodeId
            var codeId = _codeIds[_random.Next(_codeIds.Count)];

            // 随机选择CouponInstanceId（30%概率使用优惠券）
            string? couponInstanceId = null;
            if (_random.NextDouble() < 0.3)
            {
                if (_couponInstanceIds.Count == 0)
                {
                    _logger.LogWarning("CouponInstanceId列表为空，跳过优惠券使用");
                }
                else
                {
                    couponInstanceId = _couponInstanceIds[_random.Next(_couponInstanceIds.Count)];
                }
                //couponInstanceId = _couponInstanceIds[_random.Next(_couponInstanceIds.Count)];
            }

            return new OrderCreateRequestDto
            {
                OrderAmount = orderAmount,
                CodeId = codeId,
                CouponInstanceId = couponInstanceId,
                PayMethod = "6", // 固定为微信主扫支付
            };
        }
    }
}